package com.dhcc.sds.busi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.CdcDictionaryMapper;
import com.dhcc.cdc.busi.dao.CdcEpisodeMapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.busi.dao.SdcBusiQcMrlistMapper;
import com.dhcc.sdc.busi.entity.SdcBusiQcMrlistEntity;
import com.dhcc.sds.base.dao.SdsQcentityMapper;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.dao.SdsMedicalGroupMapper;
import com.dhcc.sds.busi.service.ISdsMedicalGroupService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.standard.dto.CdcEpisodeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author zhangdc
 * @version 1.0
 * @date 2021/6/22 9:44
 */
@Service("sdsMedicalGroupService")
public class SdsMedicalGroupServiceImpl extends BaseServiceImpl<CdcEpisodeMapper, CdcEpisodeEntity> implements ISdsMedicalGroupService {

    @Autowired
    private ICdcEpisodeService cdcEpisodeService;

    @Autowired
    private ISdsQcincaseService sdsQcincaseService;

    @Autowired
    private CdcEpisodeMapper cdcEpisodeMapper;

    @Resource
    private CdcDictionaryMapper cdcDictionaryMapper;
    @Resource
    private SdsMedicalGroupMapper sdsMedicalGroupMapper;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private SdsQcentityMapper sdsQcentityMapper;
    @Autowired
    private SdcBusiQcMrlistMapper sdcBusiQcMrlistMapper;
    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private SysProperties sysPro;

    @Override
    public List<CdcEpisodeDto> pageEpisode(Page<CdcEpisodeEntity> page, Map<String, Object> params) {
        /*List<CdcEpisodeEntity> page1 = cdcEpisodeService.page(page, params);*/
        List<CdcEpisodeDto> cdcEpisodeDtos = CollUtil.newArrayList();
        //表单状态：全部
        List<CdcEpisodeEntity> page1 = cdcEpisodeMapper.pageByDate(page, params);
        for (CdcEpisodeEntity cdcEpisodeEntity : page1){
            Long qcincaseId = sdsQcincaseService.isGroup(cdcEpisodeEntity.getId());
            CdcEpisodeDto cdcEpisodeDto = new CdcEpisodeDto();
            BeanUtil.copyProperties(cdcEpisodeEntity, cdcEpisodeDto);
            cdcEpisodeDto.setQcincaseId(qcincaseId);
            Long busAdmTypeId = cdcEpisodeEntity.getBusAdmTypeId();
            Long busAdmStatusId = cdcEpisodeEntity.getBusAdmStatusId();
            CdcDictionaryEntity cdcDictionaryEntity = cdcDictionaryMapper.selectById(busAdmTypeId);
            CdcDictionaryEntity cdcDictionaryEntity1 = cdcDictionaryMapper.selectById(busAdmStatusId);
            if ("I".equals(cdcDictionaryEntity.getCode()) && !"C".equals(cdcDictionaryEntity1.getCode())){
                cdcEpisodeDtos.add(cdcEpisodeDto);
            }
        }
        return cdcEpisodeDtos;
    }

    @Override
    public JSONObject findFormStatus() {
        JSONObject jsObj = new JSONObject();
        jsObj.put("","");
        jsObj.put("1", "已入组");
        jsObj.put("2", "未入组");
        jsObj.put("3", "已排除");
        return jsObj;
    }

    @Override
    public List<CdcEpisodeDto> pageEpisodeByDateAndFormStatus(Page<CdcEpisodeDto> page, Map<String, Object> map) {
        //就诊类型
        CdcDictionaryEntity dictionaryEntity = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "I");
        //就诊状态
        CdcDictionaryEntity dictionaryEntity2 = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_status", "C");
        map.put("busAdmTypeId", dictionaryEntity.getId());
        map.put("busAdmStatusId", dictionaryEntity2.getId());

        if (CommonUtil.isEmpty(map.get("admLocId"))) {
            List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
            map.put("userLinkDepts", deptIds);
        }

        List<CdcEpisodeDto> episodeDtoList =  sdsMedicalGroupMapper.selectAllByDateAndFormStatus(page, map);

        // 是否启用过程质控
        String enableIPQCModule = CdcConfigCache.me().getValueByKey("SDS", "EnableIPQCModule");
        if (!CommonUtil.equals(map.get("searchType"), "2")) {
            for (int i = episodeDtoList.size() - 1; i >= 0; i--) {
                CdcEpisodeDto cdcEpisodeDto = episodeDtoList.get(i);
                Long episodeId = cdcEpisodeDto.getId();
                String entityId = cdcEpisodeDto.getEntityId();
                if (CommonUtil.isNotEmpty(entityId)) {
                    SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(entityId);
                    episodeDtoList.get(i).setEntityName(sdsQcentityEntity.getBtDesc());
                }
                // 如果开启过程质控模块
                if (CommonUtil.equals(enableIPQCModule, "Y")) {
                    // 查询在院入组病种
                    SdcBusiQcMrlistEntity sdcBusiQcMrlistEntity = new SdcBusiQcMrlistEntity();
                    sdcBusiQcMrlistEntity.setEpisodeId(episodeId);
                    sdcBusiQcMrlistEntity.setState("I");
                    sdcBusiQcMrlistEntity = sdcBusiQcMrlistMapper.selectOne(sdcBusiQcMrlistEntity);
                    if (CommonUtil.isNotEmpty(sdcBusiQcMrlistEntity)) {
                        SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(sdcBusiQcMrlistEntity.getEntityId());
                        episodeDtoList.get(i).setAdmEntityName(sdsQcentityEntity.getBtDesc());
                    }
                }
            }
        } else {
            for (int i = episodeDtoList.size() - 1; i >= 0; i--) {
                CdcEpisodeDto cdcEpisodeDto = episodeDtoList.get(i);
                String entityId = cdcEpisodeDto.getEntityId();
                if (CommonUtil.isNotEmpty(entityId)) {
                    SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(entityId);
                    episodeDtoList.get(i).setAdmEntityName(sdsQcentityEntity.getBtDesc());
                }
            }
        }

        return episodeDtoList;
    }

    @Override
    @Transactional
    public String createExcel(Map<String, Object> map) {
        List<CdcEpisodeDto> episodeDtoList =  sdsMedicalGroupMapper.selectAllByDateAndFormStatus(map);
        // 是否启用过程质控
        String enableIPQCModule = CdcConfigCache.me().getValueByKey("SDS", "EnableIPQCModule");
        if (!CommonUtil.equals(map.get("searchType"), "2")) {
            for (int i = episodeDtoList.size() - 1; i >= 0; i--) {
                CdcEpisodeDto cdcEpisodeDto = episodeDtoList.get(i);
                Long episodeId = cdcEpisodeDto.getId();
                String entityId = cdcEpisodeDto.getEntityId();
                if (CommonUtil.isNotEmpty(entityId)) {
                    SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(entityId);
                    String str = "";
                    if (CommonUtil.equals(map.get("formStatus"),"3")) {
                        if (cdcEpisodeDto.getIsAuto()==1) {
                            str = "（系统排除）";
                        } else if (cdcEpisodeDto.getIsAuto()==0){
                            str = "（手动排除）";
                        }
                    }
                    episodeDtoList.get(i).setEntityName(sdsQcentityEntity.getBtDesc() + str);
                }
                // 如果开启过程质控模块
                if (CommonUtil.equals(enableIPQCModule, "Y")) {
                    // 查询在院入组病种
                    SdcBusiQcMrlistEntity sdcBusiQcMrlistEntity = new SdcBusiQcMrlistEntity();
                    sdcBusiQcMrlistEntity.setEpisodeId(episodeId);
                    sdcBusiQcMrlistEntity.setState("I");
                    sdcBusiQcMrlistEntity = sdcBusiQcMrlistMapper.selectOne(sdcBusiQcMrlistEntity);
                    if (CommonUtil.isNotEmpty(sdcBusiQcMrlistEntity)) {
                        SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(sdcBusiQcMrlistEntity.getEntityId());
                        episodeDtoList.get(i).setAdmEntityName(sdsQcentityEntity.getBtDesc());
                    }
                }
            }
        } else {
            for (int i = episodeDtoList.size() - 1; i >= 0; i--) {
                CdcEpisodeDto cdcEpisodeDto = episodeDtoList.get(i);
                String entityId = cdcEpisodeDto.getEntityId();
                if (CommonUtil.isNotEmpty(entityId)) {
                    SdsQcentityEntity sdsQcentityEntity  = sdsQcentityMapper.selectById(entityId);
                    String str = "";
                    if (CommonUtil.equals(map.get("formStatus"),"3")) {
                        if (cdcEpisodeDto.getIsAuto()==1) {
                            str = "（系统排除）";
                        } else if (cdcEpisodeDto.getIsAuto()==0){
                            str = "（手动排除）";
                        }
                    }
                    episodeDtoList.get(i).setAdmEntityName(sdsQcentityEntity.getBtDesc() + str);
                }
            }
        }

        String filePath = sysPro.getSysHome()+"file_download/sds/medicalgroup/";
        File file = new File(filePath);
        if (!file.exists()) file.mkdirs();
        String fileName = "单病种病例导出数据_" + com.dhcc.core.framework.util.DateUtil.getDays() + ".xlsx";
        File outFile = new File(filePath + fileName);
        try {
            EasyExcel.write(new FileOutputStream(outFile), CdcEpisodeDto.class).sheet("入组病例列表").doWrite(episodeDtoList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
